//@login & register
const express = require("express")
const router = express.Router()

const passport = require("passport")
const multer = require("multer")
const fs = require("fs")

const Profile = require("../../models/Profile")
//$route GET api/profiles/test
//@desc  返回的请求的json数据
//@access public
router.get("/test",(req,res)=>{
    res.json({msg:"profile works"})
})

//图片上传存储
let storage = multer.diskStorage({
    destination:'public/uploadImages',
    filename:function (req, file, cb) {
        let fileFormat = (file.originalname).split(".");
        cb(null, fileFormat[0] + Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})
let upload = multer({
    storage:storage
})
//let imgPath2=''
router.post('/uploadimg',upload.single('file'),async (req,res)=>{
    let imgPath = req.file.path.replace(/public/,"")//将文件路径中的public\去掉，否则会和静态资源配置冲突
    console.log("imgPath:",imgPath);
    // req.body.imgPath=imgPath
    
    // imgPath2=imgPath
    console.log("上传时：",imgPath);
    console.log(req.body);
    res.json({
        imgPath:imgPath
    })
})

//$route POST api/profiles/add
//@desc  创建信息接口
//@access Private
router.post("/add",passport.authenticate("jwt",{session:false}),(req,res) => {
    const profileFields = {}
    console.log("reqbody1:",req.body);
    if(req.body.name) profileFields.name=req.body.name
    // if (req.body.imgPath){
    //     profileFields.imgPath = req.body.imgPath;
    // }else{
    //     profileFields.imgPath = 'http://localhost:5000'+imgPath2
    // }
    if (req.body.imgPath) profileFields.imgPath = req.body.imgPath;
    if (req.body.sex) profileFields.sex = req.body.sex;
    if ( req.body.address) profileFields.address = req.body.address;
    if ( req.body.time) profileFields.time = req.body.time;
    if ( req.body.people) profileFields.people = req.body.people;
    if ( req.body.phone) profileFields.phone = req.body.phone;
    console.log(req.body);
    new Profile(profileFields).save().then(data => {
        res.json({
            data,
            status:200,
            message:"创建成功！",
        })
    })
})

//$route GET api/profiles
//@desc  查询所有信息接口
//@access Private
router.get("/",passport.authenticate("jwt",{session:false}),(req,res) => {
    Profile.find()
           .then(data => {
            if(!data){
                return res.status(404).json('没有任何内容')
            }
            res.json({
                data,
                status:200,
                message:"获取数据成功！",
                total:data.length
            })
           })
           .catch(err => res.status(404).json(err))
})

//$route GET api/profiles/:id
//@desc  查询单个信息接口
//@access Private
router.get("/:name",passport.authenticate("jwt",{session:false}),(req,res) => {
    Profile.find({name:req.params.name})
           .then(data => {
            if(!data){
                return res.status(404).json('没有任何内容')
            }
            res.json({
                data,
                status:200,
                message:"查询数据成功！",
                total:data.length
            })
           })
           .catch(err => res.status(404).json(err))
})


// router.post('/uploadimg',upload.single('file'),async (ctx,next)=>{
//     let imgPath = ctx.req.file.path.replace(/public/,"")
//     console.log("imgPath:",imgPath);
//     ctx.body={
//         imgPath:imgPath
//     }
// })

//$route POST api/profiles/edit
//@desc  编辑信息接口
//@access Private
router.post("/edit/:id",passport.authenticate("jwt",{session:false}),(req,res) => {
    const profileFields = {}
    console.log("reqbody2:",req.body);
    if ( req.body.name) profileFields.name = req.body.name;
    // if (imgPath2){
    //     profileFields.imgPath = 'http://localhost:5000'+imgPath2   
    // }else{
    //     profileFields.imgPath = req.body.imgPath;
    // }
    if (req.body.imgPath) profileFields.imgPath = req.body.imgPath;
    if (req.body.sex) profileFields.sex = req.body.sex;
    if ( req.body.address) profileFields.address = req.body.address;
    if ( req.body.time) profileFields.time = req.body.time;
    if ( req.body.people) profileFields.people = req.body.people;
    if ( req.body.phone) profileFields.phone = req.body.phone;
    
    Profile.findOneAndUpdate(
        {_id:req.params.id},
        {$set:profileFields},
        {new:true},
    ).then(data => res.json({
        data,
        status:200,
        message:"编辑成功！",
        total:data.length
    }))

})

//$route POST api/profiles/delete
//@desc  删除信息接口
//@access Private
router.delete("/delete/:id",passport.authenticate("jwt",{session:false}),(req,res) => {
    //以下方法可以删，但会报错，进程崩掉
    // Profile.deleteOne({_id:req.params.id})
    //         .then(profile => {
    //             profile.save()
    //                     .then(profile => res.json(profile))
    //         })
    //         .catch(err => res.status(404).json('删除失败！'))

    //以下方法暂时可行
    Profile.deleteOne({_id:req.params.id})
    .then(profile => res.json({
        status:200,
        message:"删除成功！",
    }))
    .catch(err => res.json({
        status:404,
        message:"删除成功！",
    }))
    
    //以下方法remove()无效
    // Profile.findById({_id:req.params.id})
    // .then(profile=> {
    //     console.log(req.params.id);
    //     console.log(typeof req.params.id);
        
    //     profile.remove()
    //         .then(profile=> {
    //             console.log('数据删除成功');
    //             res.json(profile)
    //         }).catch(err => res.status(404).json('删除失败！'))
    // }).catch(err=> {
    // console.log(err)
    // })
})
module.exports = router